"""
角色管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.extensions import db
from app.models import Role, Menu

roles_bp = Blueprint('roles', __name__, url_prefix='/api/roles')


@roles_bp.route('/all', methods=['GET'])
@jwt_required()
def get_all_roles():
    """获取所有角色（不分页）"""
    try:
        roles = Role.query.all()
        return jsonify({
            'roles': [role.to_dict() for role in roles]
        }), 200
    except Exception as e:
        return jsonify({'message': f'获取角色列表失败: {str(e)}'}), 500


@roles_bp.route('', methods=['GET'])
@jwt_required()
def get_roles():
    """获取角色列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        
        query = Role.query
        
        if search:
            query = query.filter(Role.name.contains(search))
        
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        roles = [role.to_dict() for role in pagination.items]
        
        return jsonify({
            'roles': roles,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取角色列表失败: {str(e)}'}), 500


@roles_bp.route('', methods=['POST'])
@jwt_required()
def create_role():
    """创建角色"""
    try:
        data = request.get_json()
        name = data.get('name')
        description = data.get('description', '')
        menu_ids = data.get('menu_ids', [])
        
        if not name:
            return jsonify({'message': '角色名称不能为空'}), 400
        
        if Role.query.filter_by(name=name).first():
            return jsonify({'message': '角色名称已存在'}), 400
        
        role = Role(name=name, description=description)
        
        # 关联菜单
        if menu_ids:
            menus = Menu.query.filter(Menu.id.in_(menu_ids)).all()
            role.menus = menus
        
        db.session.add(role)
        db.session.commit()
        
        return jsonify({
            'message': '角色创建成功',
            'role': role.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建角色失败: {str(e)}'}), 500


@roles_bp.route('/<int:role_id>', methods=['PUT'])
@jwt_required()
def update_role(role_id):
    """更新角色"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({'message': '角色不存在'}), 404
        
        data = request.get_json()
        
        # 更新名称
        if 'name' in data:
            if data['name'] != role.name:
                if Role.query.filter_by(name=data['name']).first():
                    return jsonify({'message': '角色名称已存在'}), 400
                role.name = data['name']
        
        # 更新描述
        if 'description' in data:
            role.description = data['description']
        
        # 更新菜单关联
        if 'menu_ids' in data:
            menu_ids = data['menu_ids']
            if menu_ids:
                menus = Menu.query.filter(Menu.id.in_(menu_ids)).all()
                role.menus = menus
            else:
                role.menus = []
        
        db.session.commit()
        
        return jsonify({
            'message': '角色更新成功',
            'role': role.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新角色失败: {str(e)}'}), 500


@roles_bp.route('/<int:role_id>', methods=['DELETE'])
@jwt_required()
def delete_role(role_id):
    """删除角色"""
    try:
        role = Role.query.get(role_id)
        if not role:
            return jsonify({'message': '角色不存在'}), 404
        
        # 检查是否有用户使用此角色
        if role.users:
            return jsonify({'message': '该角色下还有用户，无法删除'}), 400
        
        db.session.delete(role)
        db.session.commit()
        
        return jsonify({'message': '角色删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除角色失败: {str(e)}'}), 500